package com.uphone.mvpdemo.pro.activity.login;

import androidx.lifecycle.LifecycleOwner;

import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.radish.baselibrary.utils.EncryptUtils;
import com.radish.baselibrary.utils.LogUtils;
import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;
import com.uphone.mvpdemo.MyApp;
import com.uphone.mvpdemo.base.mvp.BasePAV;
import com.uphone.mvpdemo.http.ApiService;
import com.uphone.mvpdemo.http.FailureConsumer;
import com.uphone.mvpdemo.http.RxSchedulers;
import com.uphone.mvpdemo.http.SuccessfulConsumer;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by hzy on 2019/1/18
 * LoginPresenter
 *
 * @author hzy
 *
 */
public class LoginPresenter extends BasePAV<LoginContract.View> implements LoginContract.Presenter {

    @Inject
    LoginPresenter() {

    }

    @Override
    public void postLogin(String username, String password) {
        mView.showLoading();
        Map<String, String> map = new HashMap<>();
        map.put("mobile", username);
        map.put("password",  EncryptUtils.encryptMD5ToString(password));
        MyApp.apiService(ApiService.class)
                .postService("login/login", RequestBody.create(MediaType.get("application/json"), new Gson().toJson(map)))
                .compose(RxSchedulers.io_main())
                .doOnSubscribe(d -> mView.showLoading())
                .doFinally(() ->  mView.closeLoading())
                .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from((LifecycleOwner) mView)))
                .subscribe(new SuccessfulConsumer() {
                    @Override
                    public void success(String body) {
                        try {
                            JSONObject jsonObject = new JSONObject(body);
                            int status = jsonObject.getInt("status");
                            LogUtils.e("status:" + status + "  responseBean:" + body);
                            if (status != 1) {
                                ToastUtils.showShort(jsonObject.getString("msg"));
                            }
                            mView.updateView(body,status);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }, new FailureConsumer());
    }
}
